package com.wangjie.simple;

/**
 * @author jieshao
 * @date 2022/5/30 10:16
 *
 * 125. 验证回文串
 */
public class Test07 {
    public static void main(String[] args) {
        String s = "race a car";
        boolean res1 = isPalindrome1(s);
        System.out.println(res1);

        boolean res2 = isPalindrome2(s);
        System.out.println(res2);

        boolean res3 = isPalindrome3(s);
        System.out.println(res3);
    }

    public static boolean isPalindrome1(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isLetterOrDigit(c)) {
                sb.append(Character.toLowerCase(c));
            }
        }
        StringBuffer reverse = new StringBuffer(sb).reverse();
        return sb.toString().equals(reverse.toString());
    }

    public static boolean isPalindrome2(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isLetterOrDigit(c)) {
                sb.append(Character.toLowerCase(c));
            }
        }
        int left = 0;
        int right = sb.length() - 1;
        while (left < right) {
            if (Character.toLowerCase(sb.charAt(left)) != Character.toLowerCase(sb.charAt(right))) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    public static boolean isPalindrome3(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
                left++;
            }
            while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
                right--;
            }
            if (left < right) {
                if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
                    return false;
                }
                left++;
                right--;
            }
        }
        return true;
    }
}